const lru = require('lru-cache');
const _ = require('lodash');

const options = {
    max: 500,
    maxAge: 1000 * 60   //ms
}

const cache = new lru(options);

/**
 * 获取缓存
 */
Object.defineProperty(cache, 'getCache', {
    value: async function (key, fn, ...args) {
        let data = cache.get(key);
        if (_.isFunction(fn) && _.isUndefined(data)) {
            data = await fn.apply(global, args);
            cache.set(key, data);
        }
        return data;
    }
})

/**
 * 设置缓存
 */
Object.defineProperty(cache, 'setCache', {
    value: async function (key, value, maxAge = 1000 * 60) {
        cache.set(key, value, maxAge);
    }
})

module.exports = cache;